#include "at32f403a_407.h"
#include "stdio.h"
#include "input.h"


#pragma import(__use_no_semihosting)             
//标准库需要的支持函数                 
struct __FILE 
{ 
	int handle; 
	/* Whatever you require here. If the only file you are using is */ 
	/* standard output using printf() for debugging, no file handling */ 
	/* is required. */ 
}; 
/* FILE is typedef’ d in stdio.h. */ 
FILE __stdout;       
//定义_sys_exit()以避免使用半主机模式    
void _sys_exit(int x) 
{ 
	x = x; 
} 
//重定义fputc函数 
int fputc(int ch, FILE *f)
{      
	while((USART1->sts &0x40)==0);//循环发送,直到发送完毕   
	USART1->dt = (u8) ch;      
	return ch;
}

static volatile uint32_t g_milliseconds = 0;

volatile uint32_t run_time = 0;

void systick_init(void)
{    
    /* config systick clock source */
    systick_clock_source_config(SYSTICK_CLOCK_SOURCE_AHBCLK_NODIV);

    /* config systick reload value and enable interrupt */
    SysTick_Config(system_core_clock / 1000U);
}

void systick_handle(void)
{
    g_milliseconds++;
    
    input_timer_callback();
    
    if(g_milliseconds % 1000 == 0)
    {
        run_time++;
    }
}

uint32_t millis(void)
{
    return g_milliseconds;
}

void delay_ms(uint32_t ms)
{
    uint32_t start;
    uint32_t now;
    start = millis();
    
    do    
    {
        now = millis();
    }while(now - start < ms);
}

void timer_delay(uint32_t ms)
{
    while(ms--)
    {
        TMR4->pr = 999;
        tmr_flag_clear(TMR4, TMR_OVF_FLAG);
        TMR4->ctrl1_bit.tmren = 1;
        while(tmr_flag_get(TMR4, TMR_OVF_FLAG) == 0);
        TMR4->ctrl1_bit.tmren = 0;
    }
}


